package guestbook;

import com.google.appengine.api.users.UserServiceFactory;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import java.util.List;

/**
 * @author Alejandro Gomez (alejandro.gomez@fdvsolutions.com)
 *         Date: 8/18/11
 *         Time: 6:09 PM
 */
@PersistenceCapable
public final class UserCredentials {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    String userId;

    @Persistent
    String gsessionid;

    @Persistent
    boolean temporary;

    @Persistent
    String token;

    @Persistent
    String tokenSecret;

    UserCredentials makePersistent() {
        return PMF.get().getPersistenceManager().makePersistent(this);
    }

    static String getCurrentUserId() {
        return UserServiceFactory.getUserService().getCurrentUser().getUserId();
    }

    static UserCredentials forCurrentUser() {
        PersistenceManager manager = PMF.get().getPersistenceManager();
        try {
            return forCurrentUser(manager);
        } finally {
            manager.close();
        }
    }

    static void deleteCurrentUserFromStore() {
        PersistenceManager manager = PMF.get().getPersistenceManager();
        try {
            UserCredentials cred = forCurrentUser(manager);
            if (cred != null) {
                manager.deletePersistent(cred);
            }
        } finally {
            manager.close();
        }
    }

    private static UserCredentials forCurrentUser(PersistenceManager manager) {
        @SuppressWarnings("unchecked")
        List<UserCredentials> creds = (List<UserCredentials>)manager.newQuery(
                UserCredentials.class, "userId == '" + getCurrentUserId() + "'").execute();
        return creds.isEmpty() ? null : creds.get(0);
    }
}
